<template>
    <l-layout class="l-tab-page" :top="formHeight + 12">
        <template #top>
            <l-query :span="5" :labelWidth="150" :height.sync="formHeight" :items="assessedFormColmuns"
                :formData="assessedFormData" :loading="tableLoading" @search="handleSearch">
                <template #updateCycleCode>
                    <l-select :options="update_cycle_code_options" v-model="assessedFormData['updateCycleCode']"
                        @change="handleSearch" />
                </template>
                <template #regionCode>
                    <l-select :options="region_code_options" v-model="assessedFormData['regionCode']"
                        @change="handleSearch" />
                </template>
                <template #name>
                    <el-input v-model="assessedFormData['name']" :placeholder="$t('请输入')" clearable
                        @change="handleSearch" />
                </template>
                <template #muTaxQRange>
                    <l-number-range v-model="assessedFormData['muTaxQRange']" @change="handleSearch"></l-number-range>
                </template>
                <template #comprehensiveEvaluationCode>
                    <l-select :options="comprehensive_evaluation_options"
                        v-model="assessedFormData['comprehensiveEvaluationCode']" @change="handleSearch" />
                </template>
                <template #redemptionTypeCode>
                    <l-select :options="redemption_type_code_options" v-model="assessedFormData['redemptionTypeCode']"
                        @change="handleSearch" />
                </template>
            </l-query>
        </template>
        <l-panel style="padding-top:0;">
            <template #toolLeft>
                <div class="l-panel--item">
                    <l-excel-btns></l-excel-btns>
                </div>
            </template>
            <template #toolRight>
                <l-tool-btns :hasAdd="false" :hasTableSetting="true" @setting="lr_handleSettingTable">
                </l-tool-btns>
            </template>
            <l-table ref="mainTable" :loading="tableLoading" :columns="assessedTableColumns" :dataSource="tableData"
                :isPage="true" :pageTotal="tableTotal" :tablePage.sync="tableCurrentPage" @loadPageData="turnTablePage">
                <template #name="scope">
                    <a @click="handleDetails(0, scope.row)">{{ scope.row.name || '---' }}</a>
                </template>
                <template #evaluationDate="{ row, rowIndex }">
                    <span v-if="row.evaluationDate">{{ row.evaluationDate.replace("T00:00:00", "") || '---' }}</span>
                    <span v-else>---</span>
                </template>
                <template #isRequirement="{ row, rowIndex }">
                    <span v-if="row.isRequirement">{{ row.isRequirement }}</span>
                    <span v-else>---</span>
                </template>
                <template #comprehensiveEvaluationCode="{ row, rowIndex }">
                    <span v-if="row.comprehensiveEvaluationCode">{{ row.comprehensiveEvaluationCode.toUpperCase() }}</span>
                    <span v-else>---</span>
                </template>
                <template #explain="{ row, rowIndex }">
                    <span v-if="row.explain">{{ row.explain || '---' }}</span>
                    <span v-else>---</span>
                </template>
                <template #redemptionDate="{ row, rowIndex }">
                    <span v-if="row.redemptionDate">{{ row.redemptionDate.replace("T00:00:00", "") }}</span>
                    <span v-else>---</span>
                </template>
                <template #redemptionTypeCode="{ row, rowIndex }">
                    <span v-if="row.redemption.length === 0">{{ '---' }}</span>
                    <span v-else>{{ lr_dataItemName(lr_dataItem['redemption_type_code'],
                        row.redemptionTypeCode) }}</span>
                </template>
                <template #redemptionAmount="{ row, rowIndex }">
                    <span v-if="row.redemptionAmount"
                        :class="row.redemptionTypeCode === 'sanction' ? 'sanction' : 'not-sanction'">
                        {{ row.redemptionAmount }}
                    </span>
                    <span v-else>{{ '---' }}</span>
                </template>
                <template #explain1="{ row, rowIndex }">
                    <span v-if="row.redemption.length === 0">{{ '---' }}</span>
                    <span v-else>{{ row.explain1 || "---" }}</span>
                </template>
                <template #attachment="{ row, rowIndex }">
                    <a v-if="row.attachment" @click="openFile(row.attachment)">查看</a>
                    <span v-else>--</span>
                </template>

            </l-table>
        </l-panel>
        <DetailDialogForm ref="DetailDialogForm" />
        <l-dialog title="文件列表" width="400px" :modal="false" :hasBtns="false" :hasHeight="false" :hasMinBtn="true"
            placement="bottom-right" :visible.sync="loadVisible" class="file-list-dialog">
            <upload-file-list :uploadingFiles="uploadingFiles" :handleFilePreview="handleFilePreview" />
        </l-dialog>
        <l-dialog title="文件预览" :visible.sync="previewVisible" width="1000px" :height="800">
            <div v-if="!isAllowed" class="desc">
                <div class="icon">
                    <svg t="1706076437100" class="icon" viewBox="0 0 1024 1024" version="1.1"
                        xmlns="http://www.w3.org/2000/svg" p-id="1947" id="mx_n_1706076437101" width="16" height="16">
                        <path
                            d="M512 97.52381c228.912762 0 414.47619 185.563429 414.47619 414.47619s-185.563429 414.47619-414.47619 414.47619S97.52381 740.912762 97.52381 512 283.087238 97.52381 512 97.52381z m0 73.142857C323.486476 170.666667 170.666667 323.486476 170.666667 512s152.81981 341.333333 341.333333 341.333333 341.333333-152.81981 341.333333-341.333333S700.513524 170.666667 512 170.666667z m36.571429 268.190476v292.571428h-73.142858V438.857143h73.142858z m0-121.904762v73.142857h-73.142858v-73.142857h73.142858z"
                            p-id="1948" fill="#ffaa00"></path>
                    </svg>
                </div>
                <div class="tip">该类型文件不支持预览，请点击下方下载按钮下载文件进行预览</div>
            </div>
            <iframe v-if="previewUrl != ''" :src="previewUrl" class="l-iframe" ref="iframe" frameborder="0"></iframe>
            <template #btns>
                <el-button size="mini" icon="el-icon-down" type="primary" @click="downFile(`${previewFileId}`)
                    ">下载</el-button>
            </template>
        </l-dialog>
    </l-layout>
</template>

<!-- 已兑现 -->
<script>
import DetailDialogForm from "../../../enterpriseManagement/views/enterpriseList/DetailDialogForm/index";
import UploadFileList from "@/core/components/upload-preview/lrUploadFileList.vue";
import {
    assessedTableColumns, assessedapi, assessedFormColmuns, assessedFormData
} from "./columns";
export default {
    data() {
        return {
            assessedTableColumns,
            assessedapi,
            assessedFormColmuns,
            assessedFormData,
            formHeight: 44,
            tableLoading: true,
            tableData: [],
            tableTotal: 0,
            tableCurrentPage: 1,
            tablePageSize: 50,
            tableBtns: [],
            fileExt: "",
            loadVisible: false,
            uploadingFiles: [],
            previewFileId: "",
            previewUrl: "",
            previewVisible: false,
        };
    },
    components: {
        DetailDialogForm,
        UploadFileList
    },
    computed: {
        update_cycle_code_options() {
            return this.lr_dataItemOptions(this.lr_dataItem["update_cycle_code"]);
        },
        region_code_options() {
            return this.lr_dataItemOptions(this.lr_dataItem["region_code"]);
        },
        comprehensive_evaluation_options() {
            return this.lr_dataItemOptions(this.lr_dataItem["comprehensive_evaluation"]);
        },
        redemption_type_code_options() {
            return this.lr_dataItemOptions(this.lr_dataItem["redemption_type_code"]);
        },
        isAllowed() {
            return this.fileExt === "pdf"
        }
    },
    mounted() {
        this.$watch(
            () => this.assessedFormData.muTaxQRange,
            (newVal) => {
                if (newVal === "") {
                    this.assessedFormData.muTaxQRange = null;
                }
            }
        )
        this.init();
    },
    methods: {
        async openFile(folderId) {
            this.uploadingFiles = []
            if (folderId) {
                const api = window.$crud(`system/annexesfile/${folderId}/list`);
                const list = await this.$awaitWraper(api.getInfo());
                if (list.length) {
                    this.uploadingFiles = list.map(t => {
                        const point = {
                            ...t
                        };
                        const fileIcon = this.lr_getFileIcon(t.name);

                        point.icon = fileIcon.icon;
                        point.color = fileIcon.color;
                        point.name = point.f_FileName;
                        point.uid = point.f_Id;
                        point.id = point.f_Id;
                        point.isSuccess = true;

                        return point;
                    });
                    this.loadVisible = true
                    return
                }
            }
            this.$message.error('未查询到可预览文件资源');
        },
        handleFilePreview(uid) {
            const file = this.uploadingFiles.find(t => t.uid == uid);
            this.handlePreview(file);
        },
        downFile(fileId) {
            this.$downFile(`${this.apiUrl}system/annexesfile/${fileId}?token=${this.token}`);
        },
        handlePreview(file) {
            // if (file.isPreview == false && !this.isImg) {
            //   this.$message({
            //     type: "warning",
            //     message: "级别不够，无权限预览！"
            //   });
            //   return;
            // }
            this.isFile = true
            const fileExt = file.name.split(".")[file.name.split(".").length - 1];
            console.log(fileExt);
            this.fileExt = fileExt;
            const fileId = file.id || file.response.fileId;
            switch (fileExt.toLowerCase()) {
                case "xls":
                case "xlsx":
                case "docx":
                case "doc":
                case "ppt":
                case "pptx":
                case "txt":
                case "csv":
                case "html":
                case "pdf":
                case "dxf":
                    this.isFile = true
                    if (this.$validatenull(this.apiUrl)) {
                        return;
                    }
                    this.previewUrl = `${this.apiUrl}system/annexesfile/preview/${fileId}?token=${this.token}`;
                    this.previewFileId = fileId;
                    this.previewVisible = true;
                    break;
                case "jpg":
                case "gif":
                case "png":
                case "bmp":
                case "jpeg":
                case "svg":
                    this.isFile = false
                    if (this.isImg) {
                        if (file.url) {
                            this.previewUrl = file.url;
                        } else {
                            if (this.$validatenull(this.apiUrl)) {
                                return;
                            }
                            this.previewUrl = `${this.apiUrl}system/annexesfile/preview/${fileId}?token=${this.token}`;
                        }
                        this.previewVisible = true;
                    } else {
                        if (this.$validatenull(this.apiUrl)) {
                            return;
                        }
                        this.previewUrl = `${this.apiUrl}system/annexesfile/preview/${fileId}?token=${this.token}`;
                        this.previewFileId = fileId;
                        this.previewVisible = true;
                        break;
                    }

                    break;
                default:
                    // 不支持预览，就直接下载
                    this.$message.warning(`当前文件格式不支持预览${fileExt}`);
                    if (this.$validatenull(this.apiUrl)) {
                        return;
                    }
                    this.$downFile(`${this.apiUrl}system/annexesfile/${fileId}?token=${this.token}`);
                    break;
            }
        },
        handleDetails(index, row) {
            this.$refs.DetailDialogForm.open(row);
        },
        init() {
            this.loadTableData();
        },
        filterBtns(row, btns) {
            return btns;
        },
        handleSearch() {
            this.loadTableData();
        },
        turnTablePage({ rows }) {
            this.tablePageSize = rows;
            this.loadTableData(true);
        },
        async loadTableData(isNotFirst) {
            if (!isNotFirst) {
                this.tableCurrentPage = 1;
            }
            this.tableLoading = true;
            let assessedFormData = this.$deepClone(this.assessedFormData);
            assessedFormData.rows = this.tablePageSize;
            assessedFormData.page = this.tableCurrentPage;
            assessedFormData.sidx = "modifyTime";
            assessedFormData.sord = "DESC";
            let data = await this.$awaitWraper(
                assessedapi.getPage(assessedFormData)
            );
            if (data != null) {
                this.tableData = data.rows.map(i => {
                    i.evaluationDate = i.assess[i.assess.length - 1]?.evaluationDate || ""
                    i.isRequirement = i.assess[i.assess.length - 1]?.isRequirement === true ? "是" : "否"
                    i.comprehensiveEvaluationCode = i.assess[i.assess.length - 1]?.comprehensiveEvaluationCode || ""
                    i.explain = i.assess[i.assess.length - 1]?.explain || ""
                    i.redemptionTypeCode = i.redemption[i.redemption.length - 1]?.redemptionTypeCode || ""
                    i.redemptionAmount = i.redemption[i.redemption.length - 1]?.redemptionAmount || ""
                    i.explain1 = i.redemption[i.redemption.length - 1]?.explain || ""
                    i.redemptionDate = i.redemption[i.redemption.length - 1]?.redemptionDate || ""
                    i.attachment = i.redemption[i.redemption.length - 1]?.attachment || ""
                    return i;
                })
                console.log("🚀 ~ data.rows:", data.rows)
                this.tableTotal = data.records;
            } else {
                this.tableTotal = 0;
                this.tableData = [];
            }
            this.tableLoading = false;
        },
    }
}
</script>


<style scoped lang='scss'>
.sanction {
    color: red;
}

.not-sanction {
    color: green;
}

.diabled {
    color: gray;
    cursor: not-allowed !important;
}

.desc {
    width: 90%;
    height: 40px;
    box-sizing: border-box;
    line-height: 40px;
    border: 1px solid #ffe9a2;
    margin: 0 auto;
    margin-top: 20px;
    padding-left: 20px;
    background-color: #fffbe6;
    display: flex;
    align-items: center;

    .icon {
        display: flex;
        align-items: center;
        margin-right: 5px;
    }
}
</style>